package com.wechat.command;

import java.io.Serializable;
import java.time.LocalDateTime;

import com.swak.utils.time.DateTimes;
import com.wechat.msg.TextMsg;
import com.wechat.msg.TxtMsg;

import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;

/**
 * 命令
 * 
 * @author DELL
 */
@Getter
@Setter
@Accessors(chain = true)
@ToString
public class Command implements Serializable {

	private static final long serialVersionUID = 1L;
	private String from;
	private String to;
	private Commands command;
	private String createTime;
	private Format fmt = Format.Xml;
	private String md5;
	private Object data;

	public Command() {
		this.createTime = DateTimes.getMilliByTime(LocalDateTime.now()).toString();
	}

	public Command copy() {
		Command copy = new Command();
		copy.setFrom(from).setTo(to).setCommand(command).setCreateTime(createTime).setFmt(fmt).setMd5(md5)
				.setData(data);
		return copy;
	}

	public Command reply() {
		Command copy = new Command();
		copy.setFrom(to).setTo(from);
		return copy;
	}

	public Command dataForTxt(String text) {
		return this.setCommand(Commands.Msg_Req_Txt).setData(TxtMsg.of().setContent(text).toXml());
	}

	public Command dataForText(String text) {
		return this.setCommand(Commands.Msg_Req_Text).setData(TextMsg.of().setContent(text).toXml());
	}

	@SuppressWarnings("unchecked")
	public <T> T dataToMsg() {
		if (command == Commands.Msg_Req_Txt) {
			return (T) TxtMsg.fromXml(String.valueOf(data), TxtMsg.class);
		} else if (command == Commands.Msg_Req_Text) {
			return (T) TextMsg.fromXml(String.valueOf(data), TextMsg.class);
		}
		return null;
	}

	public static Command of() {
		return new Command();
	}

	public static Command cmdForAddFriend(String from, String to) {
		return Command.of().setCommand(Commands.Ser_AddFriend).setFrom(from).setTo(to);
	}

	public static Command cmdForFindFriend(String find) {
		return Command.of().setCommand(Commands.Ser_Find).setData(find);
	}

	public static Command cmdForGetInfo(String from, String to) {
		return Command.of().setCommand(Commands.Ser_GetInfo).setFrom(from).setTo(to);
	}
}